library ieee;
use ieee.std_logic_1164.all;
use ieee.std_logic_unsigned.all;

entity regfile is
    port(
    ra1, ra2, wa3: in std_logic_vector(4 downto 0);
    wd3: in std_logic_vector(31 downto 0);
    clk, we: in std_logic;
    rd1, rd2: out std_logic_vector(31 downto 0)
    );
end regfile;

architecture behav of regfile is
    type mem_t is array(31 downto 0) of std_logic_vector(31 downto 0);
    signal mem: mem_t;
begin
    process (clk, ra1, ra2, wa3, mem)
        variable ra1_addr: integer;
        variable ra2_addr: integer;
        variable wa3_addr: integer;
    begin
        ra1_addr := conv_integer(ra1);
        ra2_addr := conv_integer(ra2);
        wa3_addr := conv_integer(wa3);

        -- Escribir --
        if clk'event and clk = '1' and we = '1' then
            mem(wa3_addr) <= wd3;
        end if;

        -- Leer --
        if ra1_addr = 0 then
            rd1 <= (others => '0');
        else
            rd1 <= mem(ra1_addr);
        end if;

        if ra2_addr = 0 then
            rd2 <= (others => '0');
        else
            rd2 <= mem(ra2_addr);
        end if;
    end process;
end;
